<template>
  <div>
    <div>生成圆弧顶点</div>
    <div ref="webgl" id="webgl" style="width: 800px; height: 500px"></div>
  </div>
</template>
<script lang="ts" setup>
  import * as THREE from 'three';
  import { OrbitControls } from 'three/addons';
  // import { DRACOLoader } from 'three/examples/jsm/loaders/DRACOLoader';
  // import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';
  import { onMounted, ref } from 'vue';

  const webgl: any = ref(null);
  onMounted(() => {
    init();
  });

  function init() {
    const scene = new THREE.Scene();
    const width = 800;
    const height = 500;
    const camera = new THREE.PerspectiveCamera(30, width / height, 1, 10000);
    camera.position.set(500, 500, 500);
    camera.lookAt(scene.position);
    const render = new THREE.WebGLRenderer({
      //想把canvas画布上内容下载到本地，需要设置为true
      // preserveDrawingBuffer: true,
      // 设置对数深度缓冲区，优化深度冲突问题
      // logarithmicDepthBuffer: true,
    });
    render.setSize(width, height);
    // console.log(' webgl.value', webgl.value);

    webgl.value.appendChild(render.domElement);
    // document.body.appendChild(render.domElement);
    new OrbitControls(camera, render.domElement);
    const amLight = new THREE.AmbientLight(0xffffff);
    scene.add(amLight);
    const helper = new THREE.AxesHelper(200);
    scene.add(helper);

    const geometry = new THREE.BufferGeometry(); //创建一个几何体对象
    const R = 50; //圆弧半径
    const N = 50; //分段数量
    const sp = Math.PI / (N - 1); //两个相邻点间隔弧度
    // 批量生成圆弧上的顶点数据
    const arr: any = [];
    for (let i = 0; i < N; i++) {
      const angle = sp * i; //当前点弧度
      // 以坐标原点为中心，在XOY平面上生成圆弧上的顶点数据
      const x = R * Math.cos(angle);
      const y = R * Math.sin(angle);
      arr.push(x, y, 0);
    }
    console.log('arr', arr);

    //类型数组创建顶点数据
    const vertices = new Float32Array(arr);
    // 创建属性缓冲区对象
    //3个为一组，表示一个顶点的xyz坐标
    const attribue = new THREE.BufferAttribute(vertices, 3);
    // 设置几何体attributes属性的位置属性
    geometry.attributes.position = attribue;

    // 线材质
    const material = new THREE.LineBasicMaterial({
      color: 0xff0000, //线条颜色
    });
    // 创建线模型对象   构造函数：Line、LineLoop、LineSegments
    // const line = new THREE.Line(geometry, material);
    const line = new THREE.LineLoop(geometry, material); //线条模型对象
    scene.add(line);

    function renderFun() {
      // console.log('asdfasdf');
      render.render(scene, camera);
      requestAnimationFrame(renderFun);
    }
    renderFun();
  }
</script>
